package com.core.website.api;

import com.core.website.common.Result;
import com.core.website.common.ResultUtil;
import com.core.website.entity.Column;
import com.core.website.entity.OrgAuth;
import com.core.website.entity.Organization;
import com.core.website.entity.User;
import com.core.website.service.AuthService;
import com.core.website.service.OrganizationService;
import com.core.website.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/authApi")
public class AuthApi {
    @Autowired
    private AuthService authService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrganizationService organizationService;
    @GetMapping("/queryByOrgId")
    public Result queryByOrgId(String orgId){
        List<Column> result=authService.queryByOrgId(orgId);
        return ResultUtil.success(result);
    }
    @PostMapping("/saveOrgAuth")
    public Result saveOrgAuth(@RequestBody OrgAuth orgAuth){
        Organization organization = organizationService.queryOne(orgAuth.getOrgId());
        if(null==organization||StringUtils.isEmpty(organization.getId())){
            return ResultUtil.error(-1,"机构不存在!");
        }
        authService.saveOrgAuth(orgAuth);
        return ResultUtil.success();
    }
    @GetMapping("/queryAuth")
    public Result queryAuth(){
        User subject = (User) SecurityUtils.getSubject().getPrincipal();
        if(null==subject){
            return ResultUtil.error(-1000,"用户未登录");
        }
        User user = userService.queryInfo(subject.getId());
        if(StringUtils.isEmpty(user.getOrganizationId())){
            return ResultUtil.success(new ArrayList<>());
        }
        List<Column> result=authService.queryByOrgId(user.getOrganizationId());
        return ResultUtil.success(result);
    }
}
